/**
 * @author of2198
 * @date 2017/4/26.
 * @description
 */
import QMConst from "qm-ux/lib/QMConst";

declare let window: any;

export const getEnvXSite = () => {
  return QMConst.HOST["v_x_site"];
};

export const setCookieHash = () => {
  if (getCookie("xsite-admin-hash")) {
    return;
  }
  let hash = location.hash;
  if (hash && hash.split("?").length > 1) {
    let search = hash.split("?")[1];
    let params = search.split("&");
    for (let i = 0; i < params.length; i++) {
      let param = params[i].split("=");
      if (param.length > 1 && param[0] === "_k") {
        document.cookie =
          "xsite-admin-hash=" + param[1] + "; domain=" + document.domain;
      }
    }
  }
};

export const getCookie = c_name => {
  if (c_name.length > 0 && document.cookie.length > 0) {
    let c_start = document.cookie.indexOf(c_name + "=");
    if (c_start != -1) {
      c_start = c_start + c_name.length + 1;
      let c_end = document.cookie.indexOf(";", c_start);
      if (c_end == -1) c_end = document.cookie.length;
      return document.cookie.substring(c_start, c_end);
    }
  }
  return "";
};

export const openNewWin = url => {
  window.open(url);
};

//封装给建站openApi的http请求方法
let host = getEnvXSite();
export const $http = {
  get: function(url, params = {}) {
    const queryString = Object.keys(params)
      .map(key => key + "=" + params[key])
      .join("&");
    return new Promise((resolve, reject) => {
      fetch(url + "?" + queryString, {
        method: "GET",
        mode: "cors",
        credentials: "include",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json"
        }
      }).then(
        response => {
          if (response.status !== 200) {
            reject(response);
          } else {
            response.json().then(result => {
              resolve(result);
            });
          }
        },
        err => {
          reject(err);
        }
      );
    });
  },
  post: function(url, params = {}) {
    params = Object.assign({}, params);
    return new Promise((resolve, reject) => {
      fetch(url, {
        method: "POST",
        mode: "cors",
        credentials: "include",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json"
        },
        body: JSON.stringify(params)
      }).then(
        response => {
          if (response.status !== 200) {
            reject(response);
          } else {
            response.json().then(result => {
              resolve(result);
            });
          }
        },
        err => {
          reject(err);
        }
      );
    });
  }
};

//将时间戳转为正常时间
export const transNormalTime = timestamp => {
  let date = new Date(timestamp);
  let Y = date.getFullYear() + "-";
  let M =
    (date.getMonth() + 1 < 10
      ? "0" + (date.getMonth() + 1)
      : date.getMonth() + 1) + "-";
  let D = date.getDate();
  let h = date.getHours();
  let m = date.getMinutes();
  let s = date.getSeconds();
  return Y + M + add0(D) + " " + add0(h) + ":" + add0(m) + ":" + add0(s);

  function add0(num) {
    return num < 10 ? "0" + num : num;
  }
};

//加载js文件
export const loaderJsFile = jsSrc => {
  console.warn("建议使用xDllContext.$script");
  return new Promise((resolve, reject) => {
    let head = document.getElementsByTagName("head")[0];
    let script = document.createElement("script");
    script.type = "text/javascript";
    script.charset = "utf-8";
    script.async = true;
    script.src = jsSrc;
    head.appendChild(script);

    script.onload = function() {
      resolve();
    };

    script.onerror = function(err) {
      reject(err);
    };
  });
};

//加载css文件
export const loaderCssFile = cssSrc => {
  return new Promise((resolve, reject) => {
    let node = document.createElement("link");
    node.rel = "stylesheet";
    node.type = "text/css";
    node.href = cssSrc;
    node.onload = function() {
      resolve();
    };
    node.onerror = function(err) {
      reject(err);
    };
    document.getElementsByTagName("head")[0].appendChild(node);
  });
};
